# !/usr/bin/env python
# -*- coding: utf-8 -*-
# ------------------------------
'''
task：就是把很多个协程对象放入一个可以循环便利的空间，结束就剔除，等待就开始下一个
'''

# 导包
import asyncio


async def func1():
    print('----1----')
    return '1>>>完'

async def func2():
    print('----2----')
    await asyncio.sleep(1)
    return '2>>>完'

async def func3():
    print('----3----')
    # await asyncio.sleep(1)
    return '3>>>完'

async def main():
    task1 = asyncio.create_task(func1())
    task2 = asyncio.create_task(func2())
    task3 = asyncio.create_task(func3())
    ret = await task1
    print(ret)
    ret1 = await task2
    print(ret1)
    ret3 = await task3
    print(ret3)
    print(ret, ret1, ret3)

if __name__ == '__main__':
    asyncio.run(main())


    '''
    从结果看来并不是在task2等待的时间事件循环跑去执行task3了
    '''

async def func1():
    print('----1----')
    return '1>>>完'


async def func2():
    print('----2----')
    await asyncio.sleep(3)
    return '2>>>完'

async def func3():
    print('----3----')
    # await asyncio.sleep(1)
    return '3>>>完'

async def main():
    '''
            代码优化
    '''
    # 同样创建任务对象
    task_list = [
        asyncio.create_task(func1()),
        asyncio.create_task(func2()),
        asyncio.create_task(func3())
    ]
    # ret = asyncio.wait(task_list, timeout=2)
    # print(ret)
    ret = await asyncio.wait(task_list, timeout=2)
    print(ret)
    '''{<Task finished coro=<func3() done, defined at D:/gitcode/path of python learning/learn_py/exercise/多任务—多进程学习/协程异步学习/task对象.py:58> result='3>>>完'>, 
        <Task finished coro=<func1() done, defined at D:/gitcode/path of python learning/learn_py/exercise/多任务—多进程学习/协程异步学习/task对象.py:47> result='1>>>完'>,
        <Task finished coro=<func2() done, defined at D:/gitcode/path of python learning/learn_py/exercise/多任务—多进程学习/协程异步学习/task对象.py:52> result='2>>>完'>
    }, set()
    ret返回一个元组，其中包括已完成协程对象的信息和 经过设置之后未完成的task（done， pending）
    '''


if __name__ == '__main__':
    asyncio.run(main())




'''
另一种情况就是当我们的task列表创建成全局变量
'''


async def func1_():
    print('----1----')
    return '1>>>完'

task_list = [
        func1_(),
        func1_()
    ]

asyncio.run(asyncio.wait(task_list))   # 这里的wait会直接将协程对象加入到任务中，
# 这样做的原因是因为在创建任务对象前必须创建循环事件及asyncio.run得执行